package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redstar.HappyRefresh.mapper.TypeMapper;
import com.redstar.HappyRefresh.pojo.Result;
import com.redstar.HappyRefresh.pojo.Type;
import com.redstar.HappyRefresh.pojo.UserSubscribe;
import com.redstar.HappyRefresh.service.TypeService;
import com.redstar.HappyRefresh.service.UserSubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Autowired
    private UserSubscribeService userSubscribeService;

    @Override
    public List<String> random10Labels() { // 随机获取10个标签
        List<Type> typeList = list();
        ArrayList<String> resultLabelList = new ArrayList<>();
        int size1 = typeList.size();
        if (size1 == 0) {
            throw new RuntimeException("random10Labels方法出错：数据库中的分类数量为0");
        }
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int index = random.nextInt(size1);
            // 随机获取1个分类
            Type type = typeList.get(index);
            List<String> labelList = type.buildLabel();
            int size2 = labelList.size(); // 分类下一定存在标签
            // 随机获取1个标签
            String label = labelList.get(random.nextInt(size2));
            resultLabelList.add(label);
        }
        return resultLabelList;
    }

    @Override
    public List<Type> getTypes(Long userId) { // 查询所有分类并判断当前用户是否订阅
        // 只需要查询分类的图标，id和名称
        List<Type> allTypeList = this.list(new LambdaQueryWrapper<Type>().select(Type::getIcon, Type::getId, Type::getName).orderByDesc(Type::getId));
        if (userId != null) { // 查询当前typeService用户订阅的分类
            List<UserSubscribe> userSubscribeList = userSubscribeService.list(new LambdaQueryWrapper<UserSubscribe>().eq(UserSubscribe::getUserId, userId));
            if (ObjectUtils.isEmpty(userSubscribeList)) {
                log.info("getTypes方法：id为" + userId + "的用户未订阅分类");
            } else{
                Set<Long> subscribeTypeIdList = userSubscribeList.stream().map(UserSubscribe::getTypeId).collect(Collectors.toSet()); // 用户订阅的分类的id
                for (Type type : allTypeList) { // 记录当前用户是否订阅改分类
                    type.setUsed(subscribeTypeIdList.contains(type.getId()));
                }
            }
        }
        return allTypeList;
    }
}
